import { Form, Input, message, Modal, Popover, Select } from "antd";
import { FC, useCallback, useEffect, useState } from "react";
// import { useWindowFontSize } from "../../../../../assets/fun/configprovider";
import { getCarList, getCarMessage, getPrRegis, getPrUpdate, handlegetGoodList, ISelectList, ISelectListType } from "../../../api";
import { PopBox, PopoverBox } from "../../style";
import { withDebounce } from "../../../../../assets/fun/antiVibrationThrottlingFun";
import { useWindowFontSize } from "../../../../../assets/fun/Antd/configprovider";
// import { withDebounce } from "../../../../../assets/fun/antiVibrationThrottlingFun";


const AddCar: FC<{
    AddOpenShow: boolean
    AddCallBack: () => void
    CarOpenData?: ISelectListType
}> = ({
    AddOpenShow, AddCallBack, CarOpenData
}) => {
        const [visible, setVisible] = useState(false); //popover的开关
        const [carAllData, setAllCarData] = useState<string[]>([]);
        const [carOpenData, setCarOpenData] = useState<string[]>([]);
        const [departmentData, setDepartmentData] = useState<ISelectList[]>([]);
        const [form] = Form.useForm();
        const { setFieldsValue, resetFields } = form;
        const handleOk = async () => {
            const values = await form.validateFields();
            if(CarOpenData&&Object.keys(CarOpenData).length !== 0){
                const params = {
                    ...values,
                    id:CarOpenData.id
                }
                //修改
                const {code,msg} = (await getPrUpdate(params)) as {
                    code: number
                    msg:string
                } 
                if(code===20000){
                    message.success('修改成功')
                    resetFields()
                    AddCallBack()
                }else{
                    message.error(msg)
                }
            }else{
                // 添加
                const {code,msg} = (await getPrRegis(values)) as {
                    code: number
                    msg:string
                } 
                if(code===20000){ 
                    message.success('新增成功')
                    resetFields()
                    AddCallBack()
                }else{
                    message.error(msg)
                }
            }
        };
        const handleCancel = () => {
            resetFields()
            AddCallBack()
        };

        const handlePrefixClick = (e: React.MouseEvent) => {
            handlegetInfo()
            e.stopPropagation(); // 阻止点击 prefixSelector 时触发 Popover
        };

        //输入框的前置输入框
        const prefixSelector = () => {
            return (
                <Form.Item name={['carColor']} noStyle>
                    <Select
                        style={{ width: '6.5rem' }}
                        options={[
                            { value: "蓝", label: "蓝" },
                            { value: "黄", label: "黄" },
                            { value: "绿", label: "绿" },
                            { value: "黑", label: "黑" },
                        ]}
                        onClick={handlePrefixClick} // 阻止弹出 Popover
                    >
                    </Select>
                </Form.Item>
            );
        }
        //输入框的onchange回调
        const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
            //此函数为从所有车牌号中筛选车牌号的模糊匹配函数
            const inputValue = e.target.value;
            if (inputValue) {
                const filteredData = carAllData.filter(car => car.includes(inputValue.toUpperCase()));
                setCarOpenData(filteredData);
                if (filteredData.length > 0) {
                    setVisible(true)
                } else {
                    setVisible(false)
                }
            } else {
                setCarOpenData([]); // 如果输入框为空，则清空匹配结果
                setVisible(false); // 无数据时关闭弹出框
            }
            handlegetInfo()
        };
        //popover的内容
        const content = (
            <div style={{ width: "30rem" }}>
                {carOpenData.length > 0 && (
                    <PopBox>
                        {carOpenData.map((car, index) => (
                            <li className="li-car" key={index} onClick={() => {
                                console.log(car);
                                setFieldsValue({ carNum: car })
                                setVisible(false);
                                handlegetInfo()
                            }}>{car}</li>
                        ))}
                    </PopBox>
                )}
            </div>
        );
        //获取车辆列表
        const listCarFun = useCallback(async () => {
            const { code, msg, data } = (await getCarList()) as {
                code: number
                msg: string
                data: string[]
            }
            if (code === 20000) {
                setAllCarData(data)
            } else {
                message.error(msg)
            }
        }, [])
        //根据车牌号获取车辆信息
        const handlegetInfo =
            withDebounce(async () => {
                const carNum = form.getFieldValue(('carNum'))
                const carColor = form.getFieldValue(('carColor'))
                const params = {
                    carNum: carNum,
                    carColor: carColor
                }
                if(carNum&&carColor){
                    const { code, msg, data } = (await getCarMessage(params)) as {
                        code: number
                        msg: string
                        data: {
                            allowAmount: number
                            driverName: string
                            telPhone: string
                        }
                    }
                    if (code === 20000) {
                        if(Object.keys(data).length !== 0){
                            setFieldsValue({
                                allowAmount: data.allowAmount,
                                driverName: data.driverName,
                                telPhone: data.telPhone
                            })
                        }
                        
                    } else {
                        message.error(msg)
                    }
                }
            }, 1000);

        useEffect(() => {
            listCarFun()
        }, [listCarFun])

        useEffect(()=>{            
            if(CarOpenData){
                (Object.keys(CarOpenData).length !== 0)&&setFieldsValue(CarOpenData)
            }else{
                resetFields()
            }
        },[setFieldsValue,CarOpenData,resetFields])

        useEffect(() => {
            handlegetGoodList().then(
                res => {
                    setDepartmentData(res)
                }
            )
        }, [])

        //车牌号失去焦点时触发
        const handCarNumBlur = (e: React.FocusEvent<HTMLInputElement>) => {
            console.log(e.target.value);
            form.setFieldValue('carNum',e.target.value.toUpperCase())
        }

        return (
            <div onClick={() => setVisible(false)}>
                <Modal
                    width={useWindowFontSize(484)}
                    title={CarOpenData ? '修改车辆' : "登记车辆"}
                    open={AddOpenShow}
                    onOk={handleOk}
                    onCancel={handleCancel}
                    getContainer={false}
                    okText="确认"
                    cancelText="取消"
                >
                    <Form form={form}
                        labelCol={{ span: 7 }}
                        wrapperCol={{ span: 16 }}
                        labelAlign="right"
                        initialValues={{ carColor: "黄" }}
                    >
                        <Form.Item name="good" label="货品"
                            rules={[{ required: true, message: "请选择货品!" }]}
                        >
                            <Select
                                placeholder="请选择货品"
                                options={departmentData}>
                            </Select>
                        </Form.Item>
                        <PopoverBox>
                            <div id="popover-chilren">
                            <Popover
                                content={content}
                                trigger="click"
                                open={visible}
                                getPopupContainer={() => document.getElementById("popover-chilren") as HTMLElement}
                                title="车号匹配" placement="bottom" arrow={false} >
                                <Form.Item
                                    label="车牌号"
                                    name="carNum"
                                    // normalize={(value) => (value ? value.toUpperCase() : '')}  // 将输入值转换为大写
                                    rules={[{ required: true, message: "请输入车牌号!" },
                                    ]}
                                >
                                    <Input
                                        addonBefore={prefixSelector()}
                                        placeholder="请输入车牌号"
                                        onChange={handleInputChange}
                                        onBlur={handCarNumBlur}
                                    />
                                </Form.Item>
                            </Popover>
                            </div>
                        </PopoverBox>
                        <Form.Item
                            label="司机姓名"
                            name="driverName"
                            rules={[{ required: true, message: "请输入司机姓名!" }]}
                        >
                            <Input
                                placeholder="请输入司机姓名"
                            />
                        </Form.Item>
                        <Form.Item
                            label="手机号"
                            name="telPhone"
                            rules={[{ required: true, message: "请输入手机号" }]}

                        >
                            <Input
                                placeholder="请输入手机号"
                            />
                        </Form.Item>
                        <Form.Item
                            label="允许提货量(吨)"
                            name="allowAmount"
                            rules={[{ required: true, message: "请输入允许提货量!" },
                                //最大长度不能超过8位
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (value < 0 || value > 99999999) {
                                            return Promise.reject("重量不合适，请重新输入");
                                        }
                                        return Promise.resolve();
                                    },
                                }),
                                ({ getFieldValue }) => ({
                                    validator(_, value) {
                                        if (CarOpenData&&value < CarOpenData.allowAmount) {
                                            return Promise.reject(new Error("允许的范围必须大于上一次"));
                                        }
                                        return Promise.resolve();
                                    },
                                }),
                            ]}
                        >
                            <Input
                                type="number"
                                style={{ width: '100%' }}
                                placeholder="请输入允许提货量"
                            />
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        )
    }
export default AddCar;